<?php
class Merchant_Service_Product
{
	protected $_modelProduct;
	protected $_modelOptions = null;
	protected $_modelOptionChoose = null;
	protected $_modelOptionValue = null;
	public $statusText = array(
				"2" => "Draft",
				"1" => "Activate",
				"0" => "Deleted"
			);
    public $statusTextCn = array(
        "2" => "草稿",
        "1" => "激活",
        "0" => "删除"
    );
	public $logType = array(
				"0" => "Content Update",
				"1" => "Status Update",
				"2" => "Shelf/Warehouse Update",
			);
	public function __construct(){
		$this->_modelProduct = new Merchant_Model_Product();
	}
	
	public static function getInstance(){
		return new Merchant_Service_Product();
	}
	public static function getByProductId($id){
		$obj = new Merchant_Model_Product();
		return $obj->getByProductId($id);
	}
	
	//获取最后一个产品的ID
	public static function getMaxProductId(){
		$obj = new Merchant_Model_Product();
		return $obj->getMaxProductId();	
	}
	
	/**
	* 创建产品
	* @param array $row
	* @param array $productOptionValues
	* @param array $pictures
	* @param int $customerId
	* @return boolean|array 
	*/
	public function create($row,$productOptionValues = array(),$pictures = array(),$links=array(),$customerId = null,$package=null,$qcCon=null){
		$error = $this->validate($row,$customerId,$productOptionValues,'','',$package);
		if(!empty($error)){
			return $error;
		}
		if($this->_modelOptionValue == null){
			$this->_modelOptionValue = new Merchant_Model_ProductOptionValue();
		}
		$dbAdapter = $this->_modelOptionValue->getDbTable()->getAdapter();
		$dbAdapter->beginTransaction();
		try{
			$row["customer_id"] = $this->getCustomerId($customerId);
			$insertId = $this->_modelProduct->getDbTable()->insert($row);
			if($insertId > 0){
				//添加包装材料
				if(isset($package)){
					$ppmObj = new Merchant_Model_ProductPackageMap();
					$packageRow = array('product_id'=>$insertId,'package_id'=>$package,'warehouse_id'=>'1','ppm_last_update'=>date('Y-m-d H:i:s'));
					$ppmObj->getDbTable()->insert($packageRow);
				
				}
				foreach($productOptionValues as $key => $value){
					//查询option
					if($this->_modelOptions == null){
						$this->_modelOptions = new Merchant_Model_ProductOptions();
					}
					$option = $this->_modelOptions->getDbTable()->find($value['po_id'])->current();
					
					$insertRow = array(
						"po_id" => $value['po_id'],
						// "poc_id" => $value['poc_id'],
						"product_id" => $insertId,
					);
					if($option['po_choose_type'] == 0){
						$insertRow['poc_id'] = $value['poc_id'];
					}else{
						$insertRow['po_value'] = $value['poc_id'];
					}
					
					$this->_modelOptionValue->getDbTable()->insert($insertRow);
				}
				//添加图片
				$this->addPicture($customerId,$insertId,$row['product_sku'],$pictures);
				//添加外部链接
				$this->addLinks($links,$insertId);
				$this->writeLog($row,$insertId,"0","0","0");
				//创建成功 添加qc项
                if(!empty($qcCon)){
                    $povServiceObj = new Merchant_Service_ProductOptionValue();
                    foreach ($qcCon as $v){
                        $v['product_id']= $insertId;
                        $v['pov_add_time'] = date("Y-m-d H:i:s");
                        $povServiceObj->add($v);
                    }
                }

			}else{
				$dbAdapter->rollback();
				return array('Internal error! Please try again.');//添加失败				
			}
		}catch(Exception $e){
			//return $e->getMessage();
			$dbAdapter->rollback();
			return array('Internal error! Please try again.',$e->getMessage());//添加失败		
		}
		$dbAdapter->commit();
		
		return true;
	}
	
	/**
	* 验证产品数据
	* @param array $row
	* @param int $customerId
	* @param array $productOptionValues
	* @param boolean $edit
	* @param int $productId 如果$edit 为true 需要设置$productId
	* @return true|array  success return true or failure return array
	*/
	public function validate($row,$customerId = null,$productOptionValues = array(),$edit = false,$productId=null,$package=null){
		$customerId = $this->getCustomerId($customerId);
		$error = array();
        $tipArr=Common_Service_Get::getProduct();
		if("" == $row['product_title']){
			$error[] = $tipArr['product_title'].$tipArr['required'];
		}
		
		//产品包装
		if(isset($package)||$package!=0){
			$packageObj = new Merchant_Model_ProductPackage();
			if(!$packageObj->getPackage($package))
            $error[] = $tipArr['product_package'].$tipArr['required'];
		}
		if("" == $row['product_weight']){
            $error[] = $tipArr['product_weight'].$tipArr['required'];
		}else if(!is_numeric($row['product_weight'])){
            $error[] = $tipArr['product_weight'].$tipArr['numeric'];
		}
		if("" == $row['product_length']){
            $error[] = $tipArr['product_length'].$tipArr['required'];
		}else if(!is_numeric($row['product_length'])){
            $error[] = $tipArr['product_length'].$tipArr['numeric'];
		}
		if("" == $row['product_width']){
            $error[] = $tipArr['product_width'].$tipArr['required'];
		}else if(!is_numeric($row['product_width'])){
            $error[] = $tipArr['product_width'].$tipArr['numeric'];
		}
		if("" == $row['product_height']){
            $error[] = $tipArr['product_height'].$tipArr['required'];
		}else if(!is_numeric($row['product_height'])){
            $error[] = $tipArr['product_height'].$tipArr['numeric'];
		}
		if("" == $row['product_sku']){
            $error[] = $tipArr['product_sku'].$tipArr['required'];
		}else if($this->existsSku($customerId,$row['product_sku'],$edit,$productId)){
            $error[] = $tipArr['product_weight'].$tipArr['exists'];
		}
		
		if($this->_modelOptions == null){
			$this->_modelOptions = new Merchant_Model_ProductOptions();
		}
		foreach($productOptionValues as $key => $value){
			$option = $this->_modelOptions->getDbTable()->find($value['po_id'])->current();
			if(isset($option->po_type)){
				if($option->po_type == 1 && $value['poc_id'] == ""){
					$error[] = $option->po_name.$tipArr['required'];
				}
			}else{
				$error[] = $tipArr['product_category'].$tipArr['required'];
			}
		
		}
		return $error;
	}
	
	/**
	* 检查sku是否存在
	* @param string $sku
	* @param int $customerId
	* @param boolean $edit
	* @return boolean
	*/
	public function existsSku($customerId,$sku,$edit = false,$productId = null){
		$row = $this->_modelProduct->getByCustomerIdAndSku($this->getCustomerId($customerId),$sku);
		if(empty($row)){
			return false;
		}
		
		if($edit){//编辑时要判断相等的sku是否和当前productId相等
			 if($row->product_id != $productId) return true;
			 return false;
		}
		
		
		return true;
	}
	
	/**
	* 分页获得数据
	* @param array $condition
	* @param int $page
	* @param int $pageSize
	* @param int $customerId
	* @return array
	*/
	public function getList($condition = array(),$page=1,$pageSize=0,$customerId = null){
		$rows = $this->_modelProduct->getAll($condition,$page,$pageSize,$this->getCustomerId($customerId))->toArray();
		
		return $rows;
	}
	
	/**
	* 获得产品创建的下拉框选项
	* @return array 
	*/
	public function getSelectOptions(){
		if($this->_modelOptions == null){
			$this->_modelOptions = new Merchant_Model_ProductOptions();
		}
		if($this->_modelOptionChoose == null){
			$this->_modelOptionChoose = new Merchant_Model_ProductOptionChoose();
		}
		$options = $this->_modelOptions->getAll();
		$selects = array();
		foreach($options as $option){
			$optionChooses = $this->_modelOptionChoose->getAllByOption($option->po_id);
			$select = array(
				"id" => $option->po_id,
				"name" => $option->po_name, 
				"po_choose_type" => $option->po_choose_type, 
				"desc" => $option->po_description,
				"required" => $option->po_type,
				"options" => $optionChooses->toArray(), 
			);
			$selects[] = $select;
		}
		return $selects;
	}
	
	/**
	* 获得登录信息
	* return Zend_Session_NameSpace
	*/
	public function getLoginInfo(){
		return Merchant_Service_Customer::getInstance()->getLoginInfo();
	}
	
	/**
	* 获得创建产品图片上传的临时目录
	* return string
	*/
	public function getPictureUploadDir($customerId = null){
		$customerId = $this->getCustomerId($customerId);
		$customerDir = "../data/images/".$customerId;
		if(!file_exists($customerDir)){
			if(mkdir($customerDir)){
				chmod($customerDir,0777);
			}
		}
		return $customerDir;
	}
	

	/**
	* 上传图片后移动目录并将路径保存到数据库
	* @param int $customerId
	* @param int $productId
	* @param mix $sku
	* @rparam array $pictures
	* @return void
	*/
	public function addPicture($customerId,$productId,$sku,$pictures){
		//将图片放到data/customerId/sku下面
		$customerDir = $this->getPictureUploadDir($customerId);
		$productIdDir = $customerDir."/".$productId;
		if(!file_exists($productIdDir)){
			if(mkdir($productIdDir)){
				chmod($productIdDir,0777);
			}
		}
		//删除已经存在的图片地址
		Merchant_Model_ProductAttached::getInstance()->deleteByProductId($productId);
		if(file_exists($productIdDir)){
			foreach ($pictures as $picture){
				$oldFile = $customerDir."/".$picture;
				if(file_exists($oldFile)){
					$newFile = $productIdDir."/".$picture;
					file_put_contents($newFile,file_get_contents($oldFile));
					
					unlink($oldFile);
				}
				//将图片名称保存到数据库
				$attRow = array(
					"product_id" => $productId,
					"pa_path" => $picture,
					"pa_file_type" => "img",
					"pa_status" => 1,
					"languages_id" => $this->getLoginInfo()->lang?$this->getLoginInfo()->lang:1,
					"pa_last_update" => date("Y-m-d H:i:s"),
				);
				Merchant_Model_ProductAttached::getInstance()->getDbTable()->insert($attRow);
			}
		}
	}
	
	/**
	* 添加外部链接图片
	* @param int $productId
	* @param array $links
	* @param boolean $edit
	* @return void
	*/
	public function addLinks($links,$productId,$edit = false){
		if($edit){//修改时先删除之前的
			Merchant_Model_ProductAttached::getInstance()->deleteLinksByProductId($productId);
		}
		foreach($links as $link){
			$linksRow = array(
				"product_id" => $productId,
				"pa_path" => $link,
				"pa_file_type" => "link",
				"pa_status" => 1,
				"languages_id" => $this->getLoginInfo()->lang?$this->getLoginInfo()->lang:1,
				"pa_last_update" => date("Y-m-d H:i:s"),
			);
			Merchant_Model_ProductAttached::getInstance()->getDbTable()->insert($linksRow);
		}
	}
	
	
	/**
	* 查询当前客户id
	* @param int|null customerId
	* @return int
	*/
	public function getCustomerId($customerId = null){
		if($customerId == null){
			$loginInfo = $this->getLoginInfo();
			$customerId = $loginInfo->customer['customer_id'];
		}
		return $customerId;
	}
	
	/**
	* 获得产品信息
	* @param int $productId
	* @return array
	*/
	public function getProductInfo($productId,$customerId = null){
		$product = Merchant_Model_Product::getInstance()->getProduct($productId,$this->getCustomerId($customerId));
		if($product instanceof Zend_Db_Table_Row){
			$product = $product->toArray();
			//查找产品的关联选项
			$povServiceObj = new Merchant_Model_ProductOptionValue();
			$povs = $povServiceObj->getByProductId($productId)->toArray();
			$product['pov'] = $povs;
			//产品目录
			$product['category'] = $this->getProductCategory($productId);
			return $product;
		}
		return false;
	}
	
	/**
	* 获得产品信息
	* @param int $sku
	* @return array
	*/
	public function getProductBySku($sku,$customerId = null){
		$product = Merchant_Model_Product::getInstance()->getProductBySku($sku,$this->getCustomerId($customerId));
		if($product instanceof Zend_Db_Table_Row){
			$product = $product->toArray();
			//查找产品的关联选项
			$povServiceObj = new Merchant_Model_ProductOptionValue();
			$povs = $povServiceObj->getByProductId($product['product_id'])->toArray();
			$product['pov'] = $povs;
			//产品目录
			$product['category'] = $this->getProductCategory($product['product_id']);
			return $product;
		}
		return false;
	}
	
	/**
	* 获得产品目录
	* @param int $productId
	* @return array|false
	*/
	public function getProductCategory($productId){
		$povServiceObj = new Merchant_Model_ProductOptionValue();
		$category = $povServiceObj->getByProductId($productId,1)->current();
		if($category instanceof Zend_Db_Table_Row){
			$category = $category->toArray();
			$pocService = new Merchant_Model_ProductOptionChoose();
			$poc = $pocService->getDbTable()->find($category['poc_id'])->current();
			if($poc instanceof Zend_Db_Table_Row){
				return $poc->toArray();
			}
		}
		return false;
	}
	/**
	* 删除产品信息
	* @param int $productId
	* @return boolean
	*/
	public static  function deleteProduct($productId){
		$table = Merchant_Model_Product::getInstance()->getDbTable();
		return $table->delete($table->getAdapter()->quoteInto("product_id = ?",$productId));
	}
	
	/**
	* 更改产品状态
	* @param int $productId
	* @return boolean
	*/
	public function changeProductStatus($productId,$status){
		$table = Merchant_Model_Product::getInstance();
		$product = $this->getProductInfo($productId);
		$planService = new Merchant_Service_Plan();
		$db = $this->_modelProduct->getDbTable()->getAdapter();
		$db->beginTransaction();
		try{
			if($status == 1){//激活产品
				if($product['product_status'] != 2){
					$db->rollback();
					return "产品的状态必须是草案";
				}
			}
			if($status == 2){//取消激活产品
				if($product['product_status'] != 1){
					$db->rollback();
					return "此产品未激活";
				}
				//判断产品库存
				$ProductStocket = Merchant_Service_ProductStocket::getByProductId($product['product_id']);
				if($ProductStocket['ps_quantity'] > 0||$ProductStocket['ps_quantity_hold'] > 0){
					$db->rollback();
					return ("库存必须为空");
				}
			}
			if($status == 0){//删除
				if($product['product_status'] != 2 || $product['product_warehouse_status'] != 0){
					$db->rollback();
					return "必须是草稿状态才可以删除！";
				}
			}
			if($table->changeProductStatus($productId,$status)){
				$this->writeLog(array(),$productId,"1",$product['product_status'],$status);
				$db->commit();
				return true;
			}
		}catch(Exception $e){
			$db->rollback();
		}
		return false;
	}
	
	/**
	* 获取产品总数 
	* @param array $condition
	* @param int $customerId
	* @return int
	*/
	public function getCount($condition=array(),$customerId = null){
		return $this->_modelProduct->getCount($condition,$this->getCustomerId($customerId));
	}
	
	/**
	* 通过产品id获得产品图片
	* @param int $productId
	* @return array
	*/
	public function getProductPicture($productId){
		return Merchant_Model_ProductAttached::getInstance()->getByProductId($productId)->toArray();
	}
	/**
	* 通过产品id获得产品图片,包括上传图片和网络图片
	* @param int $productId
	* @return array
	*/
	public function getAllProductPicture($productId){
		return Merchant_Model_ProductAttached::getInstance()->getAllByProductId($productId)->toArray();
	}
	
	/**
	* 通过产品id获得产品外链图片
	* @param int $productId
	* @return array
	*/
	public function getProductLinks($productId){
		return Merchant_Model_ProductAttached::getInstance()->getLinksByProductId($productId)->toArray();
	}
	/**
	* 根据产品状态码获得状态描述
	* @param int $status
	* @return string
	*/
	public function getStatusText($status){
		
		return @$this->statusText[$status];
	}
	
	/**
	* 更新产品
	* @param int $productId
	* @param array $row
	* @param array $productOptionValues
	* @param array $pictures
	* @param int $customerId
	* @return boolean|array 
	*/
	public function update($productId,$row,$productOptionValues=array(),$pictures=array(),$links=array(),$customerId = null){
		$error = $this->validate($row,$customerId,$productOptionValues,true,$productId);
		if(!empty($error)){
			return $error;
		}
		$productInfoPre = $this->getProductInfo($productId);
		if($this->_modelOptionValue == null){
			$this->_modelOptionValue = new Merchant_Model_ProductOptionValue();
		}
		$dbAdapter = $this->_modelOptionValue->getDbTable()->getAdapter();
		$dbAdapter->beginTransaction();
		try{
			if($productInfoPre['product_warehouse_status'] >0){//第一次收货
				$dbAdapter->rollback();
				return array("Failure,the product status must  never receiving");
			}
			//判断产品库存
			$ProductStocket = Merchant_Service_ProductStocket::getByProductId($productInfoPre['product_id']);
			if($ProductStocket['ps_quantity'] > 0||$ProductStocket['ps_quantity_hold'] > 0){
				$dbAdapter->rollback();
				return array("Failure,the product quantity in warehouse must be 0");
			}
			$row["customer_id"] = $this->getCustomerId($customerId);
			$dbTable = $this->_modelProduct->getDbTable();
			$where = $dbTable->getAdapter()->quoteInto("product_id = ?",$productId);
			$updateNums = $dbTable->update($row,$where);
			
			foreach($productOptionValues as $key => $value){
				//查询option
				if($this->_modelOptions == null){
					$this->_modelOptions = new Merchant_Model_ProductOptions();
				}
				$option = $this->_modelOptions->getDbTable()->find($value['po_id'])->current();
				if($option['po_choose_type'] == 0){
					$updateRow['poc_id'] = $value['poc_id'];
				}else{
					$updateRow['po_value'] = $value['poc_id'];
				}
				
				$oWhere = $dbAdapter->quoteInto("product_id = ?",$productId);
				$oWhere .= $dbAdapter->quoteInto(" and po_id = ?",$value['po_id']);
				$this->_modelOptionValue->getDbTable()->update($updateRow,$oWhere);
			}
			//更新图片
			$this->addPicture($customerId,$productId,$row['product_sku'],$pictures);
			//添加外链图片
			$this->addLinks($links,$productId,true);
			$productInfoCur = $this->getProductInfo($productId);
			$this->writeLog($row,$productId,"0",$productInfoPre['product_status'],$productInfoCur['product_status']);
			$dbAdapter->commit();
			return true;
		}catch(Exception $e){
			$dbAdapter->rollback();
			return false;
		}
	}
	
	/**
	* 更新产品
	* @param int $productId
	* @param array $row
	* @param array $productOptionValues
	* @param array $pictures
	* @param int $customerId
	* @return boolean|array 
	*/
	public function updateQty($productId,$productOptionValues=array(),$pictures=array(),$links=array(),$customerId = null){
		
		$productInfoPre = $this->getProductInfo($productId);
		if($this->_modelOptionValue == null){
			$this->_modelOptionValue = new Merchant_Model_ProductOptionValue();
		}
		$dbAdapter = $this->_modelOptionValue->getDbTable()->getAdapter();
		$dbAdapter->beginTransaction();
		try{
			
			$row["customer_id"] = $this->getCustomerId($customerId);
			$dbTable = $this->_modelProduct->getDbTable();
			$where = $dbTable->getAdapter()->quoteInto("product_id = ?",$productId);
			$updateNums = $dbTable->update($row,$where);
			
			foreach($productOptionValues as $key => $value){
				//查询option
				if($this->_modelOptions == null){
					$this->_modelOptions = new Merchant_Model_ProductOptions();
				}
				$option = $this->_modelOptions->getDbTable()->find($value['po_id'])->current();
				if($option['po_choose_type'] == 0){
					$updateRow['poc_id'] = $value['poc_id'];
				}else{
					$updateRow['po_value'] = $value['poc_id'];
				}
				
				$oWhere = $dbAdapter->quoteInto("product_id = ?",$productId);
				$oWhere .= $dbAdapter->quoteInto(" and po_id = ?",$value['po_id']);
				$this->_modelOptionValue->getDbTable()->update($updateRow,$oWhere);
			}
			//更新图片
			$this->addPicture($customerId,$productId,$productInfoPre['product_sku'],$pictures);
			//添加外链图片
			$this->addLinks($links,$productId,true);
			$this->writeLog(array(),$productId,"0",'','','min qty update or picture update');//内容修改
			$dbAdapter->commit();
			return true;
		}catch(Exception $e){
			$dbAdapter->rollback();
			return false;
		}
	}
	/**
	 * 更新产品
	 * @param int $productId
	 * @param array $row
	 * @param array $productOptionValues
	 * @param array $pictures
	 * @param int $customerId
	 * @return boolean|array
	 */
	public function svcUpdate($productSku,$row,$customerId,$links=null,$package=null,$qcArr=null){	
		
		$product = Merchant_Model_Product::getInstance()->getProductBySku($productSku,$customerId);
		
		if(empty($product)){//判断产品是否存在
			return   $productSku."  not found....";
		}
		$productId = $product->product_id;
		
		$productInfoPre = $this->getProductInfo($productId,$customerId);
		
		$this->_modelOptionValue = new Merchant_Model_ProductOptionValue();
		
		$dbAdapter = $this->_modelOptionValue->getDbTable()->getAdapter();
		$dbAdapter->beginTransaction();
		try{
			$packageObj = new Merchant_Model_ProductPackage();
			$ppid=0;
			if($package){//判断包材
				$p=$packageObj->getPackage($package);
				if($p){					
					$updateRow = array("package_id"=>$p['pp_id']);
					if(Merchant_Model_ProductPackageMap::getInstance()->getPackage($productId)){
						if(!Merchant_Model_ProductPackageMap::getInstance()->update($updateRow, $productId)){
							throw new Exception("update package fail");
						}
					}else{
						$packageMap = array(
								"package_id"=>$p['pp_id'],
								"product_id"=>$productId,
								"warehouse_id"=>1								
								);
						Merchant_Model_ProductPackageMap::getInstance()->add($packageMap);
					}
					
				}else{
					throw new Exception(  $package. " Package not found.");
				}
			}
// 			print_r($productInfoPre);exit;
			$dbTable = Merchant_Model_Product::getInstance()->getDbTable();
			$where = $dbTable->getAdapter()->quoteInto("product_id = ?",$productId);
			
			$tempRow = array("product_last_modified"=>date("Y-m-d H:i:s"));
			if(isset($row['product_is_qc'])){//判断qc
				$tempRow['product_is_qc'] = $row['product_is_qc'];
			}
			
			$updateNums = $dbTable->update($tempRow,$where);//更新
				
			
			//添加外链图片
			if(!empty($links)){
				$this->addLinks($links,$productId,true);				
			}
			$productInfoCur = $this->getProductInfo($productId,$customerId);
			
			//创建成功 添加qc项
			if(!empty($qcArr)){
				$povServiceObj = new Merchant_Service_ProductOptionValue();
				$povServiceObj->deleteByCondition($productId,4,0);//删除qc
				foreach ($qcArr as $v){//添加qc
					$v['product_id']= $productId;
					$v['pov_add_time'] = date("Y-m-d H:i:s");
					if(!isset($v['po_id'])){
						throw new Exception("qc po_id empty");
					}
					if(!isset($v['poc_id'])){
						throw new Exception("qc poc_id empty");
					}
					if(!isset($v['po_value'])){
						throw new Exception("qc po_value empty");
					}
					$povServiceObj->add($v);
				}
			}
			
// 			return  print_r($productInfoCur,true);
			$this->writeLog($tempRow,$productId,"0",$productInfoPre['product_status'],$productInfoCur['product_status'],"svcUpdate");			
			
			$dbAdapter->commit();
			
			return true;
		}catch(Exception $e){
			$dbAdapter->rollback();
			return $e->getMessage();
		}
	}
	
	/**
	* 产品修改日志记录
	* $param array $row
	* $param int $productId
	* $param int $type
	* $param int $preStatus
	* $param int $curStatus
	* @return void
	*/
	public function writeLog($row,$productId,$type,$preStatus="",$curStatus="",$note=''){
		$noteArray = array(
			"product_sku" => "SKU",
			"product_title" => "SKUName",
			"product_length" => "lenght",
			"product_width" => "width",
			"product_height" => "height",
			"product_weight" => "weight",
			"product_declared_value" => "declare value",
		);		
		empty($note)&&$note = "";
		foreach($row as $key => $value){
			if(isset($noteArray[$key])){
				$note .= $noteArray[$key].":".$value.";";
			}
		}
		$dbTable = Merchant_Model_ProductHistory::getInstance()->getDbTable();
		$log = array(
			"ph_type" => $type,
			"product_id" => $productId,
			"ph_statu_pre" => $preStatus,
			"ph_statu_now" => $curStatus,
			"ph_note" => $note,
			"ph_add_time" => date("Y-m-d H:i:s"),
			"ph_ip" => $_SERVER['REMOTE_ADDR']
		);
		$dbTable->insert($log);
	}
	
	/**
	* 获得日志信息
	* @param int $productId
	* @param int $customerId
	* @param int $page
	* @param int $pageSize
	* @return array
	*/
	public function getLog($productId,$page,$pageSize,$customerId=null){
		$serviceObj = Merchant_Model_ProductHistory::getInstance();
		$product = $this->getProductInfo($productId,$customerId);
		$logs = $serviceObj->getByProductId($product['product_id'],$page,$pageSize)->toArray();

		foreach($logs as $key => $value){
			$logs[$key]['type'] = $this->logType[$value["ph_type"]];
			$logs[$key]['statu_pre'] = $this->statusText[$value["ph_statu_pre"]];
			$logs[$key]['statu_now'] = $this->statusText[$value["ph_statu_now"]];
		}
		return $logs;
	}
	
	/**
	* 获得日志总数
	* @param int $productId
	* @param int $customerId
	* @return int
	*/
	public function getLogCount($productId){
		$serviceObj = Merchant_Model_ProductHistory::getInstance();
		return $serviceObj->getCount($productId);
	}
	
	/**
	 * 读取字段作对比
	 * 
	 */
	public function readFiled(){
     
	}
	
	/**
	* 读取上传文件
	* @param string $fileName
	* @return array
	*/
	public function readUploadFile($fileName,$filePath){
		$columnMap = array(
			"ProductNo" => "product_sku",
			"ProductName" => "product_title",
			"Category" => "Category",
			"UOM" => "UOM",
			"Length" => "product_length" ,
			"Height" => "product_height",
			"Width" => "product_width",
			"Weight" => "product_weight" ,
			"Declare Value" => "product_declared_value",
			"Min Qty" => "Min_Qty",
		);
		$pathinfo = pathinfo($fileName);
		$fileData = array();
        
		if($pathinfo["extension"] == "xls"){
			$fileData = Merchant_Service_Upload::readEXCEL($filePath);
		}else if($pathinfo["extension"] == "csv"){
			$fileData = Merchant_Service_Upload::readCSV($filePath);
		}
		$result = array();
		if($fileData){
			foreach($fileData[0] as $key => $value){
				if(isset($columnMap[$value])){
					$fileData[0][$key] = $columnMap[$value];
				}
			}
			foreach($fileData as $key => $value){
				//将第一行value转成其他行的key
				if ($key == 0){
					continue;
				}
				foreach($value as $vKey => $vValue){
					if($fileData[0][$vKey] == "") continue;
					$result[$key][$fileData[0][$vKey]] = $vValue;
				}
			}
		}
		
		return $result;
	}
	
	/**
	* 检查上传数据有效性
	* @param array $data
	* @return array $error
	*/
	public function checkUploadData($data){
		$error = array();
		foreach($data as $key => $value){
			$poc = $this->getPoc($value['Category']);
			$productOptionValues = array();
			if($poc !== false){
				$productOptionValues[] = array(
													"poc_id" => $poc['poc_id'],
													"po_id" => $poc['po_id'],
												);
			}else{
				$productOptionValues[] = array(
													"poc_id" => $value['Category'],
													"po_id" => 0,
												);
			}
			$error[$key] = $this->validate($value,null,$productOptionValues);
		}
		return $error;
	}
	
	/**
	* 保存上传数据
	* @param array $data
	* @return void
	*/
	public function saveUploadData($data){
		foreach($data as $key => $value){
			$poc = $this->getPoc($value['Category']);
			$productOptionValues = array();
			if($poc !== false){
				$productOptionValues[] = array(
													"poc_id" => $poc['poc_id'],
													"po_id" => $poc['po_id'],
												);
			}
			unset($value['Category']);
			unset($value['UOM']);
			$this->create($value,$productOptionValues);
		}
	}
	
	
	/**
	* 通过pocId获得poc
	* @param int $pocId
	* @return array
	*/
	public function getPoc($pocId){
		$row = Merchant_Model_ProductOptionChoose::getInstance()->getDbTable()->find($pocId)->current();
		if($row instanceof Zend_Db_Table_Row){
			return $row->toArray();
		}
		return false;
	}
	
	public function delete($productId){
		$pp = new Merchant_Service_ProductProccess();
		$result = $pp->submited(0,$productId);
		return  $result['msg'];
	}
	/**
	* 产品激活
	* @param array $productIds
	* @return 
	*/
	public function activate($productIds){
		$message = array();

			foreach($productIds as $id){
				$pp = new Merchant_Service_ProductProccess($id);

				$result = $pp->submited(1);
				$message[$result['product_sku']] = $result['msg'];
			}
//		}
		return $message;
	}
	
	/**
	* 产品转为草稿
	* @param array $productIds
	* @return 
	*/
	public function inactivate($productIds){
		$message = array();
		
		foreach($productIds as $id){

			$pp = new Merchant_Service_ProductProccess($id);
			$result = $pp->submited(2);
			$message[$result['product_sku']] = $result['msg'];
		}
		return $message;
	}
	
	/**
	* 获得打印信息
	* @param array $row
	* @return 
	*/
	public function getPrintInfo($rows,$customerId = null){
		$result = array();
		$customer = new Merchant_Service_Customer();
		foreach($rows as $key => $row){
			$product = $this->getByProductId($key);
			$product['category']="";
			$category = $this->getProductCategory($key);
			$category&&$product['category']=$category['poc_value'];
// 			$product["customer"] = $customer->get($customerId);
			if($row > 0){
				for($i=0;$i<$row;$i++){					
					$result[] = $product;
				}
			}
			
		}
// 		print_r($result);exit;
		return $result;
	}
	
	public function batchAdd($rows){		
		
		$dbAdapter = $this->_modelProduct->getAdapter();
		$dbAdapter->beginTransaction();
		$msg = array();
		try {
			$count = count($rows);
			$success = 0;
			foreach($rows as $k=> $row){			
				$category = $row['category'];
				$min_qty = $row['min_qty'];
				unset($row['category']);
				unset($row['min_qty']);
				$productOptionValues = array();
				$productOptionValues[$category['po_id']] = $category;
				$productOptionValues[$min_qty['po_id']] = $min_qty;
				
				$error = $this->validate($row,null,$productOptionValues);
				
				if(empty($error)){						
					if($this->_modelOptionValue == null){
						$this->_modelOptionValue = new Merchant_Model_ProductOptionValue();
					}
					
					$row["customer_id"] = $this->getCustomerId(null);
					
					$insertId = $this->_modelProduct->getDbTable()->insert($row);
					
					if($insertId > 0){
						
						foreach($productOptionValues as $key => $value){
							//查询option
							if($this->_modelOptions == null){
								$this->_modelOptions = new Merchant_Model_ProductOptions();
							}
							$option = $this->_modelOptions->getDbTable()->find($value['po_id'])->current();
							$insertRow = array(
								"po_id" => $value['po_id'],
								// "poc_id" => $value['poc_id'],
								"product_id" => $insertId,
							);
							if($option['po_choose_type'] == 0){
								$insertRow['poc_id'] = $value['poc_id'];
							}else{
								$insertRow['po_value'] = $value['poc_id'];
							}
							$id = $this->_modelOptionValue->getDbTable()->insert($insertRow);
//							print_r($id);exit;
						}
						
						$this->writeLog($row,$insertId,"0","0","0");	
						$success++;
					}				
				}else{
					$msg[$k] = $error;					
				}	
			}	
			if($success==$count){//所有的完成了才提交
				$dbAdapter->commit();				
			}else{
				$dbAdapter->rollback();
			}
		} catch (Exception $e) {
			$dbAdapter->rollback();
			return array('Internal error! Please try again.');//添加失败		
		}
		return $msg;
	}
	
	
	/**
	* 文件下载
	*/
	public function downloadFile( $file ){
	//if (!is_file($file)) { die("<b>404 File not found!</b>"); }
	//Gather relevent info about file
	$len = filesize($file);
	$filename = basename($file);
	$file_extension = strtolower(substr(strrchr($filename,"."),1));
	//This will set the Content-Type to the appropriate setting for the file
	switch( $file_extension ) {
		case "pdf": $ctype="application/pdf"; break;
		case "exe": $ctype="application/octet-stream"; break;
		case "zip": $ctype="application/zip"; break;
		case "doc": $ctype="application/msword"; break;
		case "xls": $ctype="application/vnd.ms-excel"; break;
		case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
		case "gif": $ctype="image/gif"; break;
		case "png": $ctype="image/png"; break;
		case "jpeg":
		case "jpg": $ctype="image/jpg"; break;
		case "mp3": $ctype="audio/mpeg"; break;
		case "wav": $ctype="audio/x-wav"; break;
		case "mpeg":
		case "mpg":
		case "mpe": $ctype="video/mpeg"; break;
		case "mov": $ctype="video/quicktime"; break;
		case "avi": $ctype="video/x-msvideo"; break;
		//The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
		case "php":
		case "htm":
		case "html":
		case "txt": die("<b>Cannot be used for ". $file_extension ." files!</b>"); break;
		default: $ctype="application/force-download";
	}
	ob_end_clean();
	//Begin writing headers
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	header("Cache-Control: public");
	header("Content-Description: File Transfer");
	//Use the switch-generated Content-Type
	header("Content-Type: $ctype");
	//Force the download
	$header="Content-Disposition: attachment; filename=".$filename.";";
	header($header );
	header("Content-Transfer-Encoding: binary");
	header("Content-Length: ".$len);
	@readfile($file);
	exit;
	}
	
	
}